package com.sunlands.zlcx.usercenter.service;

import com.sunlands.zlcx.usercenter.domain.ClientDO;
import com.sunlands.zlcx.usercenter.repository.ClientRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author anjl
 */
@Slf4j
@Service
@Primary
public class ClientServiceImpl implements ClientDetailsService {

    private static final Map<String, ClientDO> clientMap = new ConcurrentHashMap<>();

    @Override
    public ClientDetails loadClientByClientId(String clientId) {
        ClientDO client = clientMap.get(clientId);
        if (Objects.isNull(client)) {
            synchronized (clientMap) {
                client = clientMap.get(clientId);
                if (Objects.isNull(client)) {
                    client = clientRepository.findOne(clientId);
                    clientMap.put(clientId, client);
                } else {
                    client = clientMap.get(clientId);
                }

            }
        }
        BaseClientDetails clientDetails = new BaseClientDetails(
                client.getClientId(),
                client.getResourceIds(),
                client.getScopes(),
                client.getGrantTypes(),
                null);

        clientDetails.setClientSecret(client.getClientSecret());
        clientDetails.setAccessTokenValiditySeconds(client.getTokenExpiredInSeconds());
        clientDetails.setRefreshTokenValiditySeconds(client.getTokenExpiredInSeconds());

        return clientDetails;
    }

    private final ClientRepository clientRepository;

    public ClientServiceImpl(ClientRepository clientRepository) {
        this.clientRepository = clientRepository;
    }
}
